<template>
  <view class="feedback-page">
    <!-- 自定义导航栏 -->
	<!--    <view class="nav-bar" :style="{ paddingTop: statusBarPx + 'px' }">
		  <view class="nav-content">
			<view class="nav-left" @click="goBack">
			  <uv-icon name="arrow-left" color="#333" size="20"></uv-icon>
			</view>
			<text class="nav-title">意见反馈</text>
			<view class="nav-right"></view>
		  </view>
		</view> -->
    
    <view class="feedback-content">
      <view class="form-container">
        <view class="form-section">
          <view class="section-title">
            <text class="title-label">反馈类型</text>
          </view>
          <view class="feedback-types">
            <view 
              v-for="item in feedbackTypes" 
              :key="item.value"
              class="type-item"
              :class="{ active: formData.type === item.value }"
              @click="selectType(item.value)"
            >
              <view class="type-radio">
                <view v-if="formData.type === item.value" class="radio-checked"></view>
              </view>
              <text class="type-label">{{ item.label }}</text>
            </view>
          </view>
        </view>
          
        <view class="form-section">
          <view class="section-title">
            <text class="title-label">问题描述</text>
          </view>
          <view class="textarea-wrapper">
            <textarea 
              v-model="formData.content"
              class="content-textarea"
              placeholder="请详细描述您遇到的问题或建议..."
              maxlength="500"
              auto-height
            ></textarea>
            <view class="word-count">{{ formData.content.length }}/500</view>
          </view>
        </view>
          
        <view class="form-section">
          <view class="section-title">
            <text class="title-label">联系方式（选填）</text>
          </view>
          <view class="input-wrapper">
            <input 
              v-model="formData.contact"
              class="contact-input"
              placeholder="请输入您的手机号或邮箱，方便我们联系您"
            />
          </view>
        </view>
          
        <view class="form-section">
          <view class="section-title">
            <text class="title-label">上传图片（选填）</text>
          </view>
          <view class="upload-container">
            <view class="image-list">
              <view
                v-for="(item, index) in uploadedImages"
                :key="index"
                class="image-item-wrapper"
              >
                <view class="image-item">
                  <image :src="item.url" mode="aspectFill" @click="previewImage(index)"/>
                  <!-- 上传中遮罩 -->
                  <view v-if="item.uploading" class="uploading-mask">
                    <uv-loading-icon mode="circle" color="#fff" size="24"></uv-loading-icon>
                    <text class="uploading-text">上传中...</text>
                  </view>
                </view>
                <view v-if="!item.uploading" class="delete-btn" @click.stop="deleteImage(index)">
                  <uv-icon name="close" size="14" color="#fff"/>
                </view>
              </view>
              <view v-if="uploadedImages.length < 3" class="upload-btn" @click="chooseImage">
                <view class="upload-icon">
                  <uv-icon name="plus" size="24" color="#999"/>
                </view>
                <text class="upload-text">添加图片</text>
              </view>
            </view>
            <view class="upload-tip">最多上传3张图片，支持jpg、png格式</view>
          </view>
        </view>
        
        <view class="submit-container">
          <view 
            class="submit-btn"
            :class="{ loading: submitLoading, disabled: !canSubmit }"
            @click="submitFeedback"
          >
            <view v-if="submitLoading" class="loading-icon">
              <uv-loading-icon mode="flower" color="#fff" size="20"></uv-loading-icon>
            </view>
            <text class="submit-text">{{ submitLoading ? '提交中...' : '提交反馈' }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { submitFeedback as submitFeedbackApi, uploadImage } from '@/api/ai'

export default {
  name: 'FeedbackPage',
  data() {
    const sys = uni.getSystemInfoSync()
    return {
      statusBarPx: sys.statusBarHeight || 0,
      formData: {
        type: '问题反馈',
        content: '',
        contact: ''
      },
      uploadedImages: [], // 已上传的图片列表 [{ url: '本地或远程URL', uploading: false, remoteUrl: '远程URL' }]
      submitLoading: false,
      feedbackTypes: [
        { label: '问题反馈', value: '问题反馈' },
        { label: '功能建议', value: '功能建议' },
        { label: '建议反馈', value: '建议反馈' }
      ],
      rules: {
        type: [
          { required: true, message: '请选择反馈类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入问题描述', trigger: 'blur' },
          { min: 10, message: '问题描述至少10个字符', trigger: 'blur' }
        ]
      },
      inputStyle: {
        border: 'none',
        borderRadius: '12rpx',
        backgroundColor: '#f8f9fa',
        padding: '24rpx',
        fontSize: '28rpx'
      },
      textareaStyle: {
        border: 'none',
        borderRadius: '12rpx',
        backgroundColor: '#f8f9fa',
        padding: '24rpx',
        fontSize: '28rpx',
        minHeight: '200rpx'
      },
      buttonStyle: {
        width: '100%',
        height: '88rpx',
        borderRadius: '20rpx',
        fontSize: '32rpx',
        fontWeight: '600'
      }
    }
  },
  computed: {
    canSubmit() {
      return this.formData.type
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },

    selectType(type) {
      this.formData.type = type
    },
    
    /**
     * 选择图片并立即上传
     */
    chooseImage() {
      uni.chooseImage({
        count: 1, // 每次只选择一张
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          this.uploadSingleImage(tempFilePath)
        },
        fail: (err) => {
          console.error('选择图片失败：', err)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },

    /**
     * 上传单张图片
     * @param {string} filePath - 本地文件路径
     */
    async uploadSingleImage(filePath) {
      // 添加到列表，显示上传中状态
      const imageItem = {
        url: filePath, // 先显示本地图片
        uploading: true,
        remoteUrl: ''
      }
      this.uploadedImages.push(imageItem)
      const currentIndex = this.uploadedImages.length - 1

      try {
        const response = await uploadImage(filePath)
        console.log('图片上传成功:', response)

        // 更新为远程URL
        this.uploadedImages[currentIndex].url = response.data
        this.uploadedImages[currentIndex].remoteUrl = response.data
        this.uploadedImages[currentIndex].uploading = false

        uni.showToast({
          title: '上传成功',
          icon: 'none',
          duration: 1500
        })
      } catch (error) {
        console.error('图片上传失败:', error)

        // 上传失败，从列表中移除
        this.uploadedImages.splice(currentIndex, 1)

        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none',
          duration: 2000
        })
      }
    },  
    
    /**
     * 删除图片
     * @param {number} index - 图片索引
     */
    deleteImage(index) {
      this.uploadedImages.splice(index, 1)
    },

    /**
     * 预览图片
     * @param {number} index - 图片索引
     */
    previewImage(index) {
      // 只预览已上传成功的图片
      const uploadedUrls = this.uploadedImages
        .filter(item => !item.uploading)
        .map(item => item.url)

      if (uploadedUrls.length === 0) {
        return
      }

      uni.previewImage({
        urls: uploadedUrls,
        current: this.uploadedImages[index].url
      })
    },
    
    /**
     * 提交反馈
     */
    async submitFeedback() {
      if (!this.canSubmit || this.submitLoading) {
        return
      }

      // 基本验证
      if (!this.formData.type) {
        uni.showToast({
          title: '请选择反馈类型',
          icon: 'none'
        })
        return
      }

      if (this.formData.content.length < 10) {
        uni.showToast({
          title: '问题描述至少10个字符',
          icon: 'none'
        })
        return
      }

      // 检查是否有图片正在上传
      const hasUploading = this.uploadedImages.some(item => item.uploading)
      if (hasUploading) {
        uni.showToast({
          title: '图片上传中，请稍候...',
          icon: 'none',
          duration: 2000
        })
        return
      }

      this.submitLoading = true

      try {
        uni.showLoading({
          title: '提交中...',
          mask: true
        })

        // 获取已上传的图片URL数组
        const imageUrls = this.uploadedImages
          .filter(item => !item.uploading && item.remoteUrl)
          .map(item => item.remoteUrl)

        const submitData = {
          type: this.formData.type, // 反馈类型（中文）
          content: this.formData.content, // 反馈内容
          mobile: this.formData.contact || undefined, // 联系方式（可选）
          images: imageUrls.length > 0 ? imageUrls : undefined // 图片URL数组（可选）
        }

        console.log('提交反馈数据:', submitData)

        await submitFeedbackApi(submitData)

        uni.hideLoading()
        this.submitLoading = false

        uni.showToast({
          title: '提交成功，感谢您的反馈！',
          icon: 'none',
          duration: 2000
        })

        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      } catch (error) {
        uni.hideLoading()
        this.submitLoading = false
        console.error('提交反馈失败:', error)
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.feedback-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

/* 导航栏 */
.nav-bar {
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 16px;
}

.nav-left, .nav-right {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.feedback-content {
  padding: 20px 16px;
  padding-bottom: 100px;
}

.form-container {
  background-color: #fff;
  border-radius: 16px;
  overflow: hidden;
}

/* 表单区块 */
.form-section {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 16px;
  padding: 20px;
}

.section-title {
  margin-bottom: 16px;
}

.title-label {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 反馈类型选择 */
.feedback-types {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.type-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  background: #f8f9fa;
  transition: all 0.3s ease;
  cursor: pointer;
	
  &.active {
    border-color: #06CBB6;
    background: rgba(6, 203, 182, 0.1);
			
    .type-radio {
      border-color: #06CBB6;
      background: #06CBB6;
    }
    
    .type-label {
      color: #06CBB6;
      font-weight: 600;
    }
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.type-radio {
  width: 16px;
  height: 16px;
  border: 2px solid #ddd;
  border-radius: 50%;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.radio-checked {
  width: 8px;
  height: 8px;
  background: #fff;
  border-radius: 50%;
}

.type-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

/* 文本区域 */
.textarea-wrapper {
  position: relative;
}

.content-textarea {
  width: 100%;
  min-height: 120px;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  background: #f8f9fa;
  font-size: 14px;
  color: #333;
  resize: none;
  line-height: 1.5;
  
  &::placeholder {
    color: #999;
  }
		
  &:focus {
    border-color: #06CBB6;
    background: #fff;
    outline: none;
  }
}

.word-count {
  position: absolute;
  bottom: 12px;
  right: 16px;
  font-size: 12px;
  color: #999;
  background: rgba(255, 255, 255, 0.8);
  padding: 2px 6px;
  border-radius: 4px;
}

/* 输入框 */
.input-wrapper {
  position: relative;
}

.contact-input {
  width: 100%;
  height: 48px;
  padding: 0 16px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  background: #f8f9fa;
  font-size: 14px;
  color: #333;
		
  &::placeholder {
    color: #999;
  }
  
  &:focus {
    border-color: #06CBB6;
    background: #fff;
    outline: none;
  }
}

/* 上传区域 */
.upload-container {
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 12px;
  }

  .image-item-wrapper {
    position: relative;
    width: 100px;
    height: 100px;
  }

  .image-item {
    position: relative;
    width: 100%;
    height: 100%;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #e0e0e0;

    image {
      width: 100%;
      height: 100%;
      display: block;
    }
  }

  .uploading-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    z-index: 5;
  }

  .uploading-text {
    font-size: 12px;
    color: #fff;
  }

  .delete-btn {
    position: absolute;
    top: -8px;
    right: -8px;
    width: 24px;
    height: 24px;
    background: linear-gradient(135deg, #ff4757 0%, #ff3838 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3);
    cursor: pointer;
    z-index: 10;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.9);
      box-shadow: 0 1px 4px rgba(255, 71, 87, 0.4);
    }
  }
		
  .upload-btn {
    width: 100px;
    height: 100px;
    border: 2px dashed #ddd;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #fafafa;
    transition: all 0.3s ease;
    cursor: pointer;

    &:hover {
      border-color: #06CBB6;
      background: rgba(6, 203, 182, 0.05);
    }

    &:active {
      transform: scale(0.98);
    }
  }
  
  .upload-icon {
    margin-bottom: 4px;
  }
  
  .upload-text {
    font-size: 12px;
    color: #999;
  }
  
  .upload-tip {
    font-size: 12px;
    color: #999;
    text-align: center;
    margin-top: 8px;
  }
}

/* 提交按钮 */
.submit-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: #fff;
}

.submit-btn {
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #06CBB6 0%, #04A89E 100%);
  border-radius: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  cursor: pointer;

  &.disabled {
    background: #e0e0e0;
    cursor: not-allowed;

    .submit-text {
      color: #999;
    }
  }

  &.loading {
    background: #ccc;
    cursor: not-allowed;
  }

  &:not(.disabled):not(.loading):active {
    transform: translateY(1px);
  }
}

.loading-icon {
  margin-right: 8px;
}

.submit-text {
  font-size: 16px;
  font-weight: 600;
  color: #fff;
}
</style>
